package com.amado.course42Socket.tcp;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wangyulong
 * @version 1.5.0
 * @date 2020/3/7 10:29
 */
public class HttpServerHelloDemo {
    // 两个常量
    private static final String CRLF = "\r\n";
    private static final String BLANK = " ";

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(80);
        long count = 0;
        while (true) {
            Socket socket = server.accept();
            System.out.println("第[" + (++count) + "]个客户端！ip为：" + socket.getInetAddress().getHostAddress() + " 访问时间： " + new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date()));
            new Thread(() -> {
                System.out.println("客户端：" + socket.getInetAddress().getHostName() + " 的请求头文件为：");
                try {
                    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
                    StringBuffer sb = new StringBuffer();
                    sb.append("HTTP/1.1").append(BLANK).append(520).append(BLANK).append("love").append(CRLF);
                    sb.append("Server:v  Server/12.19.06.14").append(CRLF).append("Date:").append(new Date()).append(CRLF);
                    sb.append("Content-type:text/html").append(CRLF);
                    String content = "<html>hello</html>";
                    sb.append("Connection:keep-alive").append(CRLF);
                    sb.append("Content-Length:").append(content.length()).append(CRLF).append(CRLF);
                    bos.write(sb.toString().getBytes());
                    bos.write(content.getBytes());
                    System.out.println("读取成功！==>" + content);
                    bos.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
